// 创建Socket.IO连接
let socket = null;
let socketConnected = false;
let currentUser = null;
let currentPrivateChat = null;
let loginForm = null;
let registerForm = null;
let loginContainer = null;
let chatContainer = null;
let messageInput = null;
let messagesDiv = null;
let usersList = null;
let currentUserSpan = null;
let privateChat = null;
let privateChatUser = null;
let privateMessages = null;
let privateMessageInput = null;
let unreadCount = null;
let loadingContainer = null;

// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', () => {
    // 初始化DOM元素
    loginForm = document.getElementById('login-form');
    registerForm = document.getElementById('register-form');
    loginContainer = document.getElementById('login-container');
    chatContainer = document.getElementById('chat-container');
    messageInput = document.getElementById('message-input');
    messagesDiv = document.getElementById('messages');
    usersList = document.getElementById('users-list');
    currentUserSpan = document.getElementById('current-user');
    privateChat = document.getElementById('private-chat');
    privateChatUser = document.getElementById('private-chat-user');
    privateMessages = document.getElementById('private-messages');
    privateMessageInput = document.getElementById('private-message-input');
    unreadCount = document.getElementById('unread-count');
    loadingContainer = document.getElementById('loading-container');

    // 绑定按钮事件
    document.getElementById('login-btn').addEventListener('click', login);
    document.getElementById('show-register-btn').addEventListener('click', showRegister);
    document.getElementById('register-btn').addEventListener('click', register);
    document.getElementById('show-login-btn').addEventListener('click', showLogin);

    // 绑定消息输入框事件
    if (messageInput) {
        messageInput.addEventListener('keypress', e => {
            if (e.key === 'Enter') sendMessage();
        });
    }

    if (privateMessageInput) {
        privateMessageInput.addEventListener('keypress', e => {
            if (e.key === 'Enter') sendPrivateMessage();
        });
    }

    // 初始化文件上传事件监听
    initializeFileUpload();

    // 初始化Socket.IO连接
    initializeSocketIO();

    // 初始化Socket.IO事件监听
    initializeSocketEvents();
});

// 初始化Socket.IO连接
function initializeSocketIO() {
    try {
        socket = io('http://localhost:3003', {
            withCredentials: true,
            transports: ['websocket', 'polling']
        });

        socket.on('connect', () => {
            console.log('Socket.IO连接成功');
            socketConnected = true;
            // Socket.IO连接成功后立即尝试自动登录
            checkAutoLogin();
        });

        socket.on('connect_error', (error) => {
            console.error('Socket.IO连接错误:', error);
            socketConnected = false;
            alert('无法连接到服务器，请确保服务器已启动');
            // 连接错误时显示登录界面
            if (loadingContainer && loginContainer) {
                loadingContainer.classList.add('hidden');
                loginContainer.classList.remove('hidden');
            }
        });

        socket.on('disconnect', () => {
            console.log('Socket.IO连接断开');
            socketConnected = false;
        });
    } catch (error) {
        console.error('Socket.IO 初始化失败:', error);
        alert('无法初始化Socket.IO连接，请确保服务器已启动');
    }
}

// 显示注册表单
function showRegister() {
    if (!loginForm || !registerForm) {
        console.error('DOM元素未初始化');
        return;
    }
    loginForm.classList.add('hidden');
    registerForm.classList.remove('hidden');
}

// 显示登录表单
function showLogin() {
    if (!loginForm || !registerForm) {
        console.error('DOM元素未初始化');
        return;
    }
    registerForm.classList.add('hidden');
    loginForm.classList.remove('hidden');
}

// 修改文件上传处理函数
function initializeFileUpload() {
    // 群聊文件上传
    const fileInput = document.getElementById('file-input');
    if (fileInput) {
        fileInput.addEventListener('change', async (e) => {
            const file = e.target.files[0];
            if (!file) return;
            
            try {
                const formData = new FormData();
                formData.append('file', file);
                
                // 从localStorage获取用户信息
                const savedUser = localStorage.getItem('chatUser');
                if (savedUser) {
                    const user = JSON.parse(savedUser);
                    formData.append('uploadedBy[username]', user.username);
                    formData.append('uploadedBy[userId]', user.userId);
                }
                
                console.log('正在上传文件，用户信息:', {
                    username: currentUser,
                    formData: Array.from(formData.entries())
                });
                
                const response = await fetch('http://localhost:3003/upload', {
                    method: 'POST',
                    body: formData
                });
                
                if (!response.ok) throw new Error('文件上传失败');
                
                const fileData = await response.json();
                console.log('文件上传成功:', fileData);
                
                // 发送文件消息
                socket.emit('chat_message', {
                    type: 'file',
                    from: {
                        username: currentUser,
                        userId: currentUser
                    },
                    file: {
                        fileId: fileData.fileId,
                        filename: fileData.filename,
                        originalname: fileData.originalname,
                        url: fileData.url,
                        mimetype: fileData.mimetype,
                        size: fileData.size
                    }
                });
                
                e.target.value = '';
            } catch (error) {
                console.error('文件上传错误:', error);
                alert('文件上传失败');
            }
        });
    }

    // 私聊文件上传
    const privateFileInput = document.getElementById('private-file-input');
    if (privateFileInput) {
        privateFileInput.addEventListener('change', async (e) => {
            if (!currentPrivateChat) {
                alert('请先选择私聊对象');
                return;
            }
            
            const file = e.target.files[0];
            if (!file) return;
            
            try {
                const formData = new FormData();
                formData.append('file', file);
                
                // 从localStorage获取用户信息
                const savedUser = localStorage.getItem('chatUser');
                if (savedUser) {
                    const user = JSON.parse(savedUser);
                    formData.append('uploadedBy[username]', user.username);
                    formData.append('uploadedBy[userId]', user.userId);
                }
                
                console.log('正在上传私聊文件，用户信息:', {
                    username: currentUser,
                    formData: Array.from(formData.entries())
                });
                
                const response = await fetch('http://localhost:3003/upload', {
                    method: 'POST',
                    body: formData
                });
                
                if (!response.ok) throw new Error('文件上传失败');
                
                const fileData = await response.json();
                console.log('私聊文件上传成功:', fileData);
                
                // 发送私聊文件消息
                socket.emit('private_message', {
                    to: currentPrivateChat.userId,
                    type: 'file',
                    from: {
                        username: currentUser,
                        userId: currentUser
                    },
                    file: {
                        fileId: fileData.fileId,
                        filename: fileData.filename,
                        originalname: fileData.originalname,
                        url: fileData.url,
                        mimetype: fileData.mimetype,
                        size: fileData.size
                    }
                });
                
                e.target.value = '';
            } catch (error) {
                console.error('文件上传错误:', error);
                alert('文件上传失败');
            }
        });
    }
}

// 检查本地存储的用户信息并自动登录
async function checkAutoLogin() {
    const loadingContainer = document.getElementById('loading-container');
    const savedUser = localStorage.getItem('chatUser');
    
    try {
        if (savedUser && socketConnected) {
            const { username } = JSON.parse(savedUser);
            currentUser = username;
            socket.emit('user_join', username);
            loginContainer.classList.add('hidden');
            chatContainer.classList.remove('hidden');
            currentUserSpan.textContent = username;
            loadingContainer.classList.add('hidden');
            return;
        }
        
        // 如果没有保存的用户信息，显示登录界面
        loadingContainer.classList.add('hidden');
        loginContainer.classList.remove('hidden');
    } catch (error) {
        console.error('自动登录失败:', error);
        // 发生错误时也显示登录界面
        loadingContainer.classList.add('hidden');
        loginContainer.classList.remove('hidden');
    }
}

// 注册函数
async function register() {
    const username = document.getElementById('reg-username').value;
    const password = document.getElementById('reg-password').value;
    const confirmPassword = document.getElementById('reg-confirm-password').value;
    
    if (!username || !password) {
        return alert('请填写用户名和密码');
    }
    
    if (password !== confirmPassword) {
        return alert('两次输入的密码不一致');
    }
    
    try {
        const response = await fetch('http://localhost:3003/auth/register', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ username, password })
        });
        
        const data = await response.json();
        if (response.ok) {
            alert('注册成功，请登录');
            showLogin();
            // 自动填充登录表单
            document.getElementById('username').value = username;
            document.getElementById('password').value = password;
        } else {
            alert(data.error || '注册失败');
        }
    } catch (error) {
        console.error('注册错误:', error);
        alert('注册失败');
    }
}

// 修改登录函数
async function login() {
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    
    if (!username || !password) {
        return alert('请填写用户名和密码');
    }

    try {
        const response = await fetch('http://localhost:3003/auth/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ username, password })
        });

        if (!response.ok) {
            const error = await response.json();
            throw new Error(error.error || '登录失败');
        }

        const data = await response.json();
        
        if (data.success) {
            // 保存完整的用户信息到本地存储
            localStorage.setItem('chatUser', JSON.stringify(data.user));
            
            // 更新当前用户信息
            currentUser = data.user.username;
            
            // 连接WebSocket
            if (!socketConnected) {
                socket.connect();
            }
            
            // 发送用户加入事件
            socket.emit('user_join', data.user.username);
            
            // 更新UI
            loginContainer.classList.add('hidden');
            chatContainer.classList.remove('hidden');
            currentUserSpan.textContent = data.user.username;
        } else {
            throw new Error(data.error || '登录失败');
        }
    } catch (error) {
        console.error('登录错误:', error);
        alert(error.message);
    }
}

// 发送群聊消息
function sendMessage() {
    const message = messageInput.value;
    if (!message) return;
    
    socket.emit('chat_message', { 
        message: message
    });
    messageInput.value = '';
}

// 发送私聊消息
function sendPrivateMessage() {
    if (!currentPrivateChat) return;
    const message = privateMessageInput.value;
    if (!message) return;
    
    socket.emit('private_message', {
        to: currentPrivateChat.userId,
        message: message
    });
    privateMessageInput.value = '';
}

// 更新用户状态
function updateStatus(status) {
    socket.emit('update_status', status);
}

// 开始私聊
async function startPrivateChat(userId, username) {
    currentPrivateChat = { userId, username };
    privateChat.classList.remove('hidden');
    privateChatUser.textContent = username;
    privateMessages.innerHTML = '';

    // 清除未读消息提示
    const unreadBadge = document.getElementById(`unread-${userId}`);
    if (unreadBadge) {
        unreadBadge.textContent = '0';
        unreadBadge.classList.add('hidden');
    }

    // 加载私聊历史记录
    socket.emit('load_private_history', { withUser: username });
}

// 关闭私聊
function closePrivateChat() {
    currentPrivateChat = null;
    privateChat.classList.add('hidden');
}

// 修改添加消息到群聊区域的函数
function appendMessage(data) {
    console.log('开始处理消息:', data); // 添加详细日志

    // 如果消息已删除，不显示
    if (data.isDeleted) {
        console.log('消息已删除，不显示');
        return;
    }

    // 检查消息数据是否完整
    if (!data || (!data.message && !data.content && !data.file)) {
        console.error('消息数据不完整:', data);
        return;
    }

    // 将content字段映射到message字段
    if (!data.message && data.content) {
        data.message = data.content;
    }

    const messageDiv = document.createElement('div');
    
    // 处理系统消息
    if (data.from && data.from.username === 'System') {
        console.log('处理系统消息:', data.message || data.content);
        messageDiv.className = 'message system';
        messageDiv.textContent = data.message || data.content;
        messagesDiv.appendChild(messageDiv);
        return;
    }

    // 确保发送者信息存在
    if (!data.from) {
        data.from = {
            username: data.username || 'unknown',
            userId: data.userId || 'unknown'
        };
    }

    console.log('发送者信息:', data.from);

    messageDiv.className = `message ${data.from.username === currentUser ? 'sent' : 'received'}`;
    if (data.messageId || data._id) {
        messageDiv.setAttribute('data-message-id', data.messageId || data._id);
    }
    
    const usernameDiv = document.createElement('div');
    usernameDiv.className = 'username';
    usernameDiv.textContent = data.from.username;
    
    const contentDiv = document.createElement('div');
    contentDiv.className = 'message-content';

    // 处理文件消息
    if (data.file) {
        console.log('处理文件消息:', data.file);
        const fileDiv = document.createElement('div');
        fileDiv.className = 'file-message';
        
        const fileIcon = document.createElement('span');
        fileIcon.className = 'file-icon';
        fileIcon.textContent = getFileIcon(data.file.mimetype);
        
        const fileInfo = document.createElement('div');
        fileInfo.className = 'file-info';
        
        const fileName = document.createElement('div');
        fileName.className = 'file-name';
        fileName.textContent = data.file.originalname || '未知文件';
        
        const fileSize = document.createElement('div');
        fileSize.className = 'file-size';
        if (data.file.size) {
            fileSize.textContent = formatFileSize(data.file.size);
        }
        
        const downloadButton = document.createElement('button');
        downloadButton.className = 'download-button';
        downloadButton.textContent = '下载';
        downloadButton.onclick = () => {
            console.log('点击下载按钮，文件信息:', data.file);
            downloadFile(data.file.filename, data.file.originalname);
        };
        
        fileInfo.appendChild(fileName);
        if (data.file.size) {
            fileInfo.appendChild(fileSize);
        }
        fileDiv.appendChild(fileIcon);
        fileDiv.appendChild(fileInfo);
        fileDiv.appendChild(downloadButton);
        
        contentDiv.appendChild(fileDiv);
    }
    
    // 添加消息文本内容
    if ((data.message || data.content) && typeof (data.message || data.content) === 'string') {
        console.log('添加文本内容:', data.message || data.content);
        const messageText = document.createElement('div');
        messageText.className = 'message-text';
        messageText.textContent = data.message || data.content;
        contentDiv.appendChild(messageText);
    }
    
    const timestampDiv = document.createElement('div');
    timestampDiv.className = 'timestamp';
    // 格式化时间戳
    const timestamp = data.timestamp || data.createdAt;
    if (timestamp) {
        const date = new Date(timestamp);
        if (!isNaN(date.getTime())) {
            timestampDiv.textContent = formatDate(date);
        }
    }
    
    const readStatusDiv = document.createElement('div');
    readStatusDiv.className = 'read-status';
    if (data.messageId || data._id) {
        readStatusDiv.setAttribute('data-message-id', data.messageId || data._id);
    }
    // 过滤掉发送者自己的已读状态
    const readByOthers = data.readBy ? data.readBy.filter(r => r.username !== data.from.username) : [];
    const readByText = readByOthers.map(r => r.username).join(', ');
    readStatusDiv.textContent = readByOthers.length > 0 ? `已读: ${readByText}` : '未读';
    
    // 添加删除按钮（仅对自己发送的消息显示）
    if (data.from.username === currentUser) {
        const deleteButton = document.createElement('button');
        deleteButton.className = 'delete-message';
        deleteButton.textContent = '删除';
        deleteButton.onclick = (e) => {
            e.stopPropagation();
            if (confirm('确定要删除这条消息吗？')) {
                socket.emit('delete_message', { messageId: data.messageId || data._id });
            }
        };
        messageDiv.appendChild(deleteButton);
    }
    
    messageDiv.appendChild(usernameDiv);
    messageDiv.appendChild(contentDiv);
    messageDiv.appendChild(timestampDiv);
    messageDiv.appendChild(readStatusDiv);
    
    messagesDiv.appendChild(messageDiv);
    messagesDiv.scrollTop = messagesDiv.scrollHeight;
    
    // 如果不是自己发的消息，标记为已读
    if (data.from.username !== currentUser && data.from.username !== 'System' && (data.messageId || data._id)) {
        socket.emit('message_read', { messageId: data.messageId || data._id });
    }

    console.log('消息处理完成'); // 添加完成日志
}

// 格式化日期
function formatDate(date) {
    const now = new Date();
    const diff = now - date;
    const oneDay = 24 * 60 * 60 * 1000;
    
    // 如果是今天的消息，只显示时间
    if (diff < oneDay && date.getDate() === now.getDate()) {
        return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
    }
    
    // 如果是昨天的消息
    if (diff < 2 * oneDay && date.getDate() === now.getDate() - 1) {
        return `昨天 ${date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })}`;
    }
    
    // 如果是今年的消息
    if (date.getFullYear() === now.getFullYear()) {
        return date.toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' });
    }
    
    // 其他情况显示完整日期
    return date.toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' });
}

// 修改添加消息到私聊区域的函数
function appendPrivateMessage(data) {
    // 如果消息已删除，不显示
    if (data.isDeleted) return;

    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${data.sent ? 'sent' : 'received'}`;
    messageDiv.setAttribute('data-message-id', data.messageId);
    
    const usernameDiv = document.createElement('div');
    usernameDiv.className = 'username';
    usernameDiv.textContent = data.fromUsername;
    
    const contentDiv = document.createElement('div');
    contentDiv.className = 'message-content';
    
    // 处理文件消息
    if (data.type === 'file' || (data.file && Object.keys(data.file).length > 0)) {
        const fileDiv = document.createElement('div');
        fileDiv.className = 'file-message';
        
        const fileIcon = document.createElement('span');
        fileIcon.className = 'file-icon';
        fileIcon.textContent = getFileIcon(data.file.mimetype);
        
        const fileInfo = document.createElement('div');
        fileInfo.className = 'file-info';
        
        const fileName = document.createElement('div');
        fileName.className = 'file-name';
        fileName.textContent = data.file.originalname || '未知文件';
        
        const fileSize = document.createElement('div');
        fileSize.className = 'file-size';
        if (data.file.size) {
            fileSize.textContent = formatFileSize(data.file.size);
        }
        
        const downloadButton = document.createElement('button');
        downloadButton.className = 'download-button';
        downloadButton.textContent = '下载';
        downloadButton.onclick = () => downloadFile(data.file.filename, data.file.originalname);
        
        fileInfo.appendChild(fileName);
        if (data.file.size) {
            fileInfo.appendChild(fileSize);
        }
        fileDiv.appendChild(fileIcon);
        fileDiv.appendChild(fileInfo);
        fileDiv.appendChild(downloadButton);
        
        contentDiv.appendChild(fileDiv);
    }
    
    // 添加消息文本内容
    if (data.message && typeof data.message === 'string') {
        const messageText = document.createElement('div');
        messageText.className = 'message-text';
        messageText.textContent = data.message;
        contentDiv.appendChild(messageText);
    }

    const timestampDiv = document.createElement('div');
    timestampDiv.className = 'timestamp';
    const timestamp = data.timestamp || data.createdAt;
    if (timestamp) {
        const date = new Date(timestamp);
        if (!isNaN(date.getTime())) {
            timestampDiv.textContent = formatDate(date);
        }
    }

    const readStatusDiv = document.createElement('div');
    readStatusDiv.className = 'read-status';
    // 过滤掉发送者自己的已读状态
    const readByOthers = data.readBy ? data.readBy.filter(r => r.username !== data.fromUsername) : [];
    const readByText = readByOthers.map(r => r.username).join(', ');
    readStatusDiv.textContent = readByOthers.length > 0 ? `已读: ${readByText}` : '未读';
    
    // 添加删除按钮（仅对自己发送的消息显示）
    if (data.fromUsername === currentUser) {
        const deleteButton = document.createElement('button');
        deleteButton.className = 'delete-message';
        deleteButton.textContent = '删除';
        deleteButton.onclick = (e) => {
            e.stopPropagation();
            if (confirm('确定要删除这条消息吗？')) {
                socket.emit('delete_message', { messageId: data.messageId });
            }
        };
        messageDiv.appendChild(deleteButton);
    }
    
    messageDiv.appendChild(usernameDiv);
    messageDiv.appendChild(contentDiv);
    messageDiv.appendChild(timestampDiv);
    messageDiv.appendChild(readStatusDiv);
    
    privateMessages.appendChild(messageDiv);
    privateMessages.scrollTop = privateMessages.scrollHeight;
    
    if (!data.sent) {
        socket.emit('message_read', { messageId: data.messageId });
    }
}

// 更新在线用户列表
function updateUsersList(users) {
    usersList.innerHTML = '';
    users.forEach(user => {
        if (user.username === currentUser) return;
        if (user.status !== 'online') return; // 只显示在线用户
        
        const li = document.createElement('li');
        const statusSpan = document.createElement('span');
        statusSpan.className = `user-status status-${user.status}`;
        
        // 添加未读消息计数器
        const unreadBadge = document.createElement('span');
        unreadBadge.className = 'badge hidden';
        unreadBadge.id = `unread-${user.userId}`;
        
        li.appendChild(statusSpan);
        li.appendChild(document.createTextNode(user.username));
        li.appendChild(unreadBadge);
        li.onclick = () => startPrivateChat(user.userId, user.username);
        
        usersList.appendChild(li);
    });
}

// 初始化Socket.IO事件监听
function initializeSocketEvents() {
    // Socket.IO 事件监听
    socket.on('chat_message', data => {
        console.log('收到群聊消息:', data); // 添加详细日志
        try {
            // 如果是私聊消息且不是发给当前用户的，则不显示
            if (data.type === 'private' && 
                data.to && 
                data.to.username !== currentUser && 
                data.from.username !== currentUser) {
                console.log('跳过不相关的私聊消息');
                return;
            }
            appendMessage(data);
        } catch (error) {
            console.error('处理群聊消息时出错:', error);
        }
    });

    socket.on('private_message', data => {
        console.log('收到私聊消息:', data); // 添加详细日志
        try {
            if (currentPrivateChat && 
                ((data.from && currentPrivateChat.userId === data.from.userId) || 
                 (data.fromUsername === currentPrivateChat.username))) {
                console.log('显示私聊消息到当前对话');
                // 如果私聊窗口已打开，直接显示消息
                appendPrivateMessage({
                    ...data,
                    sent: false,
                    fromUsername: data.from ? data.from.username : data.fromUsername
                });
            } else {
                console.log('更新未读消息计数');
                // 更新用户列表中的未读消息计数
                const userId = data.from ? data.from.userId : data.fromUsername;
                const unreadBadge = document.getElementById(`unread-${userId}`);
                if (unreadBadge) {
                    const count = parseInt(unreadBadge.textContent || '0') + 1;
                    unreadBadge.textContent = count;
                    unreadBadge.classList.remove('hidden');
                }
            }
        } catch (error) {
            console.error('处理私聊消息时出错:', error);
        }
    });

    socket.on('user_joined', data => {
        console.log('用户加入:', data); // 添加日志
        updateUsersList(data.onlineUsers);
    });

    socket.on('user_left', data => {
        console.log('用户离开:', data); // 添加日志
        // 从在线用户列表中移除离线用户
        const userElement = Array.from(usersList.children)
            .find(li => li.textContent.includes(data.username));
        if (userElement) {
            usersList.removeChild(userElement);
        }
    });

    socket.on('user_status_changed', data => {
        console.log('用户状态改变:', data); // 添加日志
        updateUsersList(data.onlineUsers);
        
        // 如果是当前私聊的用户状态改变，可能需要关闭私聊窗口
        if (currentPrivateChat && currentPrivateChat.userId === data.userId && data.status !== 'online') {
            closePrivateChat();
        }
    });

    socket.on('message_history', messages => {
        console.log('收到历史消息:', messages); // 添加详细日志
        try {
            messagesDiv.innerHTML = '';
            messages.forEach(message => {
                try {
                    if (message.type === 'private') {
                        // 如果是私聊消息，检查是否应该显示
                        if (message.to && (message.to.username === currentUser || message.from.username === currentUser)) {
                            appendMessage(message);
                        }
                    } else {
                        // 群聊消息直接显示
                        appendMessage(message);
                    }
                } catch (error) {
                    console.error('处理单条历史消息时出错:', error, message);
                }
            });
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        } catch (error) {
            console.error('处理历史消息时出错:', error);
        }
    });

    socket.on('private_history', messages => {
        console.log('私聊历史:', messages); // 添加日志
        privateMessages.innerHTML = '';
        messages.forEach(message => {
            appendPrivateMessage({
                ...message,
                sent: message.from ? message.from.username === currentUser : message.fromUsername === currentUser
            });
        });
        privateMessages.scrollTop = privateMessages.scrollHeight;
    });

    socket.on('message_deleted', data => {
        console.log('消息删除:', data); // 添加日志
        // 从群聊和私聊中移除被删除的消息
        const messageElements = document.querySelectorAll(`[data-message-id="${data.messageId}"]`);
        messageElements.forEach(element => {
            // 如果是消息元素，移除整个消息
            if (element.classList.contains('message')) {
                element.remove();
            }
            // 如果是已读状态元素，更新状态
            else if (element.classList.contains('read-status')) {
                element.textContent = '消息已删除';
            }
        });
    });

    // 添加错误处理
    socket.on('error', error => {
        console.error('Socket.IO错误:', error);
    });

    socket.on('connect_error', error => {
        console.error('Socket.IO连接错误:', error);
    });
}

// 添加文件大小格式化函数
function formatFileSize(bytes) {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 修改文件下载函数
function downloadFile(filename, originalname) {
    if (!filename || !originalname) {
        alert('文件信息不完整，无法下载');
        return;
    }
    
    fetch(`http://localhost:3003/upload/${encodeURIComponent(filename)}`, {
        method: 'GET',
        headers: {
            'Accept': 'application/octet-stream'
        }
    })
    .then(response => {
        if (!response.ok) {
            if (response.status === 404) {
                throw new Error('文件不存在');
            }
            throw new Error('文件下载失败');
        }
        return response.blob();
    })
    .then(blob => {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.style.display = 'none';
        a.href = url;
        a.download = originalname;
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);
    })
    .catch(error => {
        console.error('文件下载错误:', error);
        alert(error.message || '文件下载失败');
    });
}

// 添加获取文件图标的辅助函数
function getFileIcon(mimetype) {
    if (!mimetype) return '📄';
    
    if (mimetype.startsWith('image/')) return '🖼️';
    if (mimetype.startsWith('video/')) return '🎥';
    if (mimetype.startsWith('audio/')) return '🎵';
    if (mimetype.includes('pdf')) return '📕';
    if (mimetype.includes('word')) return '📘';
    if (mimetype.includes('excel') || mimetype.includes('spreadsheet')) return '📗';
    if (mimetype.includes('powerpoint') || mimetype.includes('presentation')) return '📙';
    if (mimetype.includes('zip') || mimetype.includes('rar') || mimetype.includes('7z')) return '📦';
    
    return '📄';
} 